package mobile.pubcrawler.ui;

import java.util.ArrayList;

import mobile.pubcrawler.PubCrawlerUI;
import mobile.pubcrawler.R;
import mobile.pubcrawler.model.DataModel;
import mobile.pubcrawler.model.DataModelLocation;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Contacts.People;
import android.telephony.SmsManager;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;


public class EditSMS extends Activity {
	
	private static final int PICK_CONTACT = 1;
	private Button next;
	private Button saveAsDefault;
	private EditText msg;

	 @Override
	 public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.sms);
        
        //SharePreferences are used in order to store the default SMS message
        final String PREF_FILE_NAME="PrefFile";
        SharedPreferences preferences = getSharedPreferences(PREF_FILE_NAME, MODE_PRIVATE);
        msg =(EditText) findViewById(R.id.smsTextEdit);
        msg.setText(preferences.getString("defaultMSG", "This is the first time you use the SMS feature."));
        msg.setText(msg.getText().toString()+"\n"+createFeedString());
        
        next = (Button) findViewById(R.id.smsNextButton);
        saveAsDefault = (Button) findViewById(R.id.smsSaveAsDefault);
        
        next.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// Choose recipient from contacts
				Intent intent = new Intent(Intent.ACTION_PICK, People.CONTENT_URI); 
		        startActivityForResult(intent, PICK_CONTACT); 
			}
		});
        
        //saves the current Text in the EditText as default SMS as shared preference
        saveAsDefault.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				 SharedPreferences preferences = getSharedPreferences(PREF_FILE_NAME, MODE_PRIVATE);
				 SharedPreferences.Editor editor = preferences.edit();
				 editor.putString("defaultMSG", msg.getText().toString());
				 editor.commit();
				}
			});
	 	}
	 
	    protected void sendInvites(String[] numbers) {
	    	for (String phoneNo : numbers) {
	    		sendSMS(phoneNo,
	    				msg.getText().toString()+createFeedString());
			}
	    }

	    
		private void sendSMS(String phoneNo, String msg) {
			PendingIntent pi = PendingIntent.getActivity(this, 0,
		            new Intent(this, EditSMS.class), 0);                
		        SmsManager sms = SmsManager.getDefault();
		        sms.sendTextMessage(phoneNo, null, msg, pi, null); 
		        Toast.makeText(getBaseContext(), 
						"Sending SMS...", 
						Toast.LENGTH_SHORT).show();
		}

		//copied from Joseph's Facebook.java, 
		//returns a string containing all chosen locations of the current pubcrawl
	    private String createFeedString()
	    {
	    	String feed = "";
	    	ArrayList<DataModelLocation> selectedLocations = DataModel.getInstance().getSelectedLocations();
			for(int i = 0; i < selectedLocations.size(); i++){ //DataModelLocation l : selectedLocations){
				if(i!=0)
					feed += "\n";//a new line to separate the different establishments
				feed += selectedLocations.get(i).getName();
				if(i!=(selectedLocations.size()-1))
					feed += ",";			
			}
			return feed;
	    }
		
	    @Override 
	    public void onActivityResult(int reqCode, int resultCode, Intent data) { 
	      super.onActivityResult(reqCode, resultCode, data); 
	     
	      switch (reqCode) {
	        case (PICK_CONTACT) : 
	          if (resultCode == Activity.RESULT_OK) { 
	            Uri contactData = data.getData(); 
	            Cursor c =  managedQuery(contactData, null, null, null, null); 
	            if (c.moveToFirst()) { 
	              //get the selected entry's phone number 
	              String phoneNo = c.getString(c.getColumnIndexOrThrow(People.NUMBER));
	              //Send the SMS plus the selected pubs
	              sendSMS(phoneNo, msg.getText().toString()+"\n"/*+createFeedString()*/);
	            } 
	          } 
	          break; 
	      } 
	    } 

		
		//----------------- Menu inflaters and listeners -------------------
	    public boolean onCreateOptionsMenu(Menu menu) {
	        MenuInflater inflater = getMenuInflater();
	        inflater.inflate(R.menu.mainmenu, menu);
	        return true;
	    }
	    
	    /* Handles item selections */
	    public boolean onOptionsItemSelected(MenuItem item) {
	        switch (item.getItemId()) {
	        case R.id.menuMainMenu:
	        	PubCrawlerUI.getInstance().startMainUI();
	            return true;
	        case R.id.menuSettings:
	        	PubCrawlerUI.getInstance().startSettingsUI();
	            return true;
	        case R.id.menuQuit:
	            System.exit(0);
	            return true;
	        }
	        return false;
	    }
}
